package com.wzp.yyptproject.service;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wzp.yyptproject.entity.User;
import com.wzp.yyptproject.repository.UserRepository;
import com.wzp.yyptproject.request.UserRequest;
import com.wzp.yyptproject.request.UserRequestZhuCe;
import com.wzp.yyptproject.until.MD5Util;
import com.wzp.yyptproject.until.MD5Util1;
import com.wzp.yyptproject.until.MD5Util2;
import com.wzp.yyptproject.until.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.annotations.DynamicUpdate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;

import org.springframework.data.domain.Pageable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import javax.servlet.ServletException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Random;

@Service
@Slf4j

public class UserServiceimp implements UserService {
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private IMailService iMailService;

    public String loginCode(Integer code) {
        List<Integer> list = redisTemplate.opsForList().range("checkCode", 0, 1);
        if (list.get(0).equals(code)) {
            return "sucess";
        } else {
            return " file";
        }
    }

    public String getChickCode() {
        final String source = "1908253674";
        StringBuilder str = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 4; i++) {
            str.append(source.charAt(random.nextInt(source.length() - 1)));
        }
        String data = str.toString();
//      redisTemplate.opsForValue().set("logincode",data);
        redisUtils.set("checkCode", data);
        redisUtils.expire("checkCode", 60);
        return data;
    }

    @Override
    public String pswdLogin(String uname, String upassword, String uidcard) {
        User user = null;
        try {
            user = userRepository.findAndByUnameAndUpasswordAndUidcard(uname, MD5Util2.EncoderByMd5(upassword), uidcard);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if ( user != null) {
           if (user.getUstatus()==1){
            return "success";
           }else {
               return "failed1";
           }
        }
        return "failed";
    }

    @Override
    public String MessLogin(String uname, String uphonenum, String uidcard, String checkCode) {
        Object code = redisUtils.get("checkCode");
        log.info("验证码" + code);
        if (checkCode.equals(code)) {
            User user = userRepository.findAndByUnameAndUphonenumAndUidcard(uname, uphonenum, uidcard);
            if (user != null) {
                if (user.getUstatus() == 1) {
                    return "success";
                } else {
                    return "failed1";
                }
            }
        }
            return "failed";
        }
//    @Override
//    public boolean findAndByUemail(String uemail) {
//        User user =userRepository.findAndByUemail(uemail);
//        if (userRepository.findAndByUemail(uemail)!=null){
//            if (user.getUlevel()==0){
//                log.info("ceshi"+user.getUlevel());
//                user.setUlevel(1);
//                log.info("ceshi"+user.getUlevel());
//                userRepository.save(user);
//                return true;
//            }
//        }
//        return false;
//    }

    @Override
    public String addUser(String uname, String uphonenum, String uidcard, String phonecode, String ucode, String upassword, String uemail) {
        String subject = "主题：天津市人民医院预约平台";
        String content = "内容：你正在天津市人民医院进行邮箱激活，如是你本人操作请点击激活进行激活邮箱 " +
//              "<a href= \"http://localhost:8080/#/checkCode?ucode="+user.getUcode()+"\">激活请点击:"+user.getUcode()+"<a/>"+
                "<a href=\"http://localhost:8001/user/checkCode?ucode=" + ucode + "\">激活请点击:" + ucode + "</a>";
//      <a href=\"http://localhost:8080/user/checkCode?code="+code+"\">激活请点击:"+code+"</a>"
        Object code = redisUtils.get("checkCode");
        User user = new User();
        log.info("验证码" + code);
        log.info(phonecode);
        if (code.equals(phonecode)) {
            user.setUname(uname);
            user.setUphonenum(uphonenum);
            user.setUidcard(uidcard);
            user.setUcode(ucode);


            try {
                user.setUpassword(MD5Util2.EncoderByMd5(upassword));
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            System.out.println(user.getUpassword());

//            user.setUpassword(upassword);
            user.setUemail(uemail);
            user.setUlevel(0);
            user.setUstatus(1);

            log.info(user.getUname());

            if (userRepository.save(user) != null) {
                log.info(user.getUemail());
                if (user.getUlevel() == 0) {
                    if (iMailService.sendHtmlMail(user.getUemail(), subject, content).equals("failed")){
                        return "failed";
                    }
                }
                log.info(user.getUemail());
                return "ok";
            }
        }
        return "false";


    }

    @Override
    public boolean findAndByUemail(String uemail) {
        String subject = "主题：天津市人民医院预约平台";
        String content = "内容：你正在天津市人民医院进行邮箱激活，如是你本人操作请点击激活进行重置密码 " +
                "<a href=\"http://localhost:8080/emailchongzhi\">重置密码</a>";

        User user = userRepository.findAndByUemail(uemail);
        if (user != null) {
            if (user.getUlevel() == 1) {
                iMailService.sendHtmlMail(uemail, subject, content);
                return true;
            }
            return false;
        }
        return false;
    }

    @Override
    public boolean updateuser(String uname, String uphonenum, String uidcard, String phonecode, String upassword) {
        Object code = redisUtils.get("checkCode");
        log.info("验证码" + code);
        log.info("用户名" + uname);
        User user = userRepository.findAndByUnameAndUphonenumAndUidcard(uname, uphonenum, uidcard);
        if (phonecode.equals(code)) {
            if (user != null) {
                log.info(user.getUname());
                user.setUpassword(MD5Util1.MD5(upassword));
                user.setUstatus(1);
                System.out.println(1);
                userRepository.save(user);

                return true;
            }
        }
        return false;

    }

    @Override
    public User findAndByUnameAndUidcard(String uname, String uidcard) {
        return userRepository.findAndByUnameAndUidcard(uname, uidcard);
    }

    @Override
    public User findAndByUUid(Integer uid) {
        return userRepository.findAndByUUid(uid);
    }

    public boolean findAndByUcode(String ucode) {
        log.info("验证码" + ucode);
        User user = userRepository.findAndByUcode(ucode);
        log.info("验证码2" + user.getUcode());
        //如果用户不等于null，把用户状态修改status=1
        if (user != null) {
            user.setUlevel(1);
            //把code验证码清空，已经不需要了
            user.setUcode("");
            System.out.println(user);
            userRepository.save(user);
            return true;
        } else {
            return false;
        }

    }

    @Override
    public Integer usercount() {
        List<User> list = userRepository.findAll();
        return list.size();
    }

    @Override
    public List<User> findAll() {
        List<User> list = userRepository.findAll();
        return list;
    }

    @Override
    public PageInfo<User> getUser(int pageNum, int pageSize) {
        //使用分页插件,核心代码就这一行
        PageHelper.startPage(pageNum, pageSize);
        List<User> userList = userRepository.findAll();
        PageInfo result = new PageInfo(userList);
        return result;
    }

    @Override
    public Page<User> findByPage(int pageCode, int pageSize) {
        System.out.println(pageCode);
        System.out.println(pageSize);
        Pageable pageable = new PageRequest(pageCode, pageSize);
        System.out.println(pageable.getPageSize());

         return userRepository.findAll(pageable);
    }


    @Override
    public boolean updateUsermess(User user) {
        User user1 =new User();
        user1.setUUid(user.getUUid());
        user1.setUname(user.getUname());
        user1.setUaddress(user.getUaddress());
        user1.setUemail(user.getUemail());
        user1.setUidcard(user.getUidcard());
        user1.setUnicheng(user.getUnicheng());
        user1.setUsex(user.getUsex());
        user1.setUage(user.getUage());
        user1.setUphonenum(user.getUphonenum());
        user1.setUpassword(user.getUpassword());
        user1.setUhead(user.getUhead());
        user1.setUcode(user.getUcode());
        user1.setUistf(user.getUistf());
        user1.setUcreatdate(user.getUcreatdate());
        user1.setUlevel(user.getUlevel());
        user1.setUcredit(user.getUcredit());
        userRepository.save(user1);
        return true;
    }

    @Override
    public boolean updatePswd(String uname, String uidcard, String upassword, String newupassword) {
        User user = userRepository.findAndByUnameAndUidcard(uname,uidcard);
        System.out.println(user.toString());
        System.out.println(upassword);
        try {
            if (user.getUpassword().equals(MD5Util2.EncoderByMd5(upassword))){
                user.setUUid(user.getUUid());
                user.setUpassword(MD5Util2.EncoderByMd5(newupassword));
                userRepository.save(user);
                return true;

            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return false;
    }
}
